const address = require('../../models/good/address');
class AddressService {
    static async getAddressList({ pageNum = 1, pageSize = 10 }, data) {
        const query = {
            ...{ userId: data.userId },
            ...(data?.name && { name: { $regex: data.name, $options: 'i' } }), // 模糊查询name字段，不区分大小写不区分大小写
            ...(data?.phone && { phone: { $regex: data.phone, $options: 'i' } }), // 模糊查询phone字段，不区分大小写
            ...(data?.address && { address: { $regex: data.address, $options: 'i' } }), // 模糊查询address字段，不区分大小写
        };
        const skip = (pageNum - 1) * pageSize;
        const limit = pageSize;
        const total = await address.countDocuments(query);
        const addressList = await address.find(query).skip(skip).limit(limit).lean();
        return {
            total,
            page: +pageNum,
            totalPages: Math.ceil(total / pageSize),
            list: addressList
        };
    }
    static async getAddressById(addressId) {
        return await address.findById(addressId).lean();
    }
    static async createAddress(addressData) {
        //默认地址唯一
        if (addressData.isDefault) {
            await address.updateMany({ userId: addressData.userId }, { isDefault: false });
        }
        return await address.create(addressData);
    }
    static async updateAddress(addressId, addressData) {
        // 如果设置为默认地址，则取消其他地址的默认状态
        if (addressData.isDefault) {
            await address.updateMany({ userId: addressData.userId }, { isDefault: false });
        }
        return await address.findByIdAndUpdate(addressId, { $set: addressData }, { new: true });
    }
    static async deleteAddress(addressId) {
        return await address.findByIdAndDelete(addressId);
    }
}
module.exports = AddressService;